package com.tarena.sentinel.study.demo02.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.sentinel.study.demo02.service.HelloService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {
    @Autowired
    private HelloService helloService;
    /**
     * 接收测试请求的接口功能
     * http://localhost:8080/hello?name=王翠花
     * hello sentinel i am 王翠花
     */
    @GetMapping("/hello")
    public String sayHi(String name){
        //准备一个sentinel资源入口 Entry
        Entry entry=null;
        String result=null;
        //对entry赋值,赋值过程会进入到sentinel系统架构计算
        //提供一个资源名称
        try{
            entry= SphU.entry("sayHi");
            result=helloService.sayHi(name);
        }catch (BlockException e){
            //entry方法抛出异常 表示入口生成失败,失败原因是sentinel拦截了
            log.info("当前资源sayHi收到了限制",e);
            result="对不起,你的请求被流量控制了";
        }finally {
            //释放entry资源
            if (entry!=null){
                entry.exit();
            }
        }
        return result;
    }
    @PostMapping("/bye")
    public String sayBye(String name){
        Entry entry=null;
        //entry=SphU.entry("sayBye");
        helloService.sayHi(name);
        return null;
    }
}













